/**
 * Copyright © 2022 易久批信息技术有限公司. All rights reserved.
 */
package com.dysm.multithread;

import java.util.concurrent.Semaphore;

/**
 * 信号量控制三个线程按顺序输出ABC
 * @author xiay
 * @since 2022/3/5 9:00 下午
 */
public class ABCSemaphorePrintTest {

    private static Semaphore a = new Semaphore(1);
    private static Semaphore b = new Semaphore(1);
    private static Semaphore c = new Semaphore(1);


    public static void main(String[] args) throws InterruptedException {
        b.acquire();
        c.acquire();
        new A().start();
        new B().start();
        new C().start();
    }

    static class A extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    a.acquire();
                    System.out.print("A");
                    b.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class B extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    b.acquire();
                    System.out.print("B");
                    c.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class C extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    c.acquire();
                    System.out.println("C");
                    a.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
